package abacab.remote;

/**
 * Defines a unique connection
 */
public final class ConnectionKey {
	/** The host's name */
	private final String	hostname;

	/** The port */
	private final int			port;

	/** The hash code */
	private final int			hashCode;

	/**
	 * Create the key
	 * 
	 * @param hostname
	 *          the host's name
	 * @param port
	 *          the port
	 * @throws NullPointerException
	 *           if the host is NULL
	 */
	public ConnectionKey(String hostname, int port) throws NullPointerException {
		this.hostname = hostname;
		this.port = port;
		this.hashCode = 31 * hostname.hashCode() + port;
	}

	@Override
	public int hashCode() {
		return this.hashCode;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		ConnectionKey other;
		try {
			other = (ConnectionKey) obj;
		}
		catch (ClassCastException e) {
			return false;
		}
		try {
			if (!this.hostname.equals(other.hostname)) {
				return false;
			}
		}
		catch (NullPointerException e) {
			// hostname should never be NULL, but in case...
			return other.hostname == null && this.port == other.port;
		}
		return this.port == other.port;
	}
}